<template>
    <div :class="{ 'show': show }" class="header-search">
      <svg-icon class-name="search-icon" icon-class="search" @click.stop="click" />
      <el-select
        ref="headerSearchSelectRef"
        v-model="search"
        :remote-method="querySearch"
        filterable
        default-first-option
        remote
        placeholder="Search"
        class="header-search-select"
        @change="change"
      >
        <el-option v-for="option in options" :key="option.item.path" :value="option.item" :label="option.item.title.join(' > ')" />
      </el-select>
    </div>
  </template>
  
  <script lang="ts" setup>
  import { ref, computed, onMounted, watchEffect, watch, nextTick } from 'vue';
  import { useRouter } from 'vue-router';
  import { PathUtils } from '@/utils/pathUtils'; // 导入 PathUtils
  import { isHttp } from '@/utils/validate';
  import { usePermissionStore } from '@/store/modules/permission';
  
  // 保留导入和类型定义，但注释掉
  // import Fuse from 'fuse.js'; // 导入 Fuse 模块
  // import { Fuse as FuseType } from 'fuse.js'; // 导入 Fuse 类型
  
  /**
   * 搜索输入框的值
   */
  const search = ref<string>('');
  
  /**
   * 搜索结果选项
   */
  const options = ref<any[]>([]);
  
  /**
   * 搜索池
   */
  const searchPool = ref<any[]>([]);
  
  /**
   * 是否显示搜索框
   */
  const show = ref<boolean>(false);
  
  /**
   * el-select 的引用
   */
  const headerSearchSelectRef = ref<HTMLElement | null>(null);
  
  /**
   * 路由器实例
   */
  const router = useRouter();
  
  /**
   * 所有路由信息
   * @returns 返回所有路由
   */
  const routes = computed(() => usePermissionStore().routes);
  
  /**
   * 点击搜索图标时触发
   */
  function click() {
    show.value = !show.value;
    if (show.value) {
      headerSearchSelectRef.value?.focus();
    }
  }
  
  /**
   * 关闭搜索框
   */
  function close() {
    headerSearchSelectRef.value?.blur();
    options.value = [];
    show.value = false;
  }
  
  /**
   * 选择搜索结果时触发
   * @param val - 选中的搜索结果
   */
  function change(val: any) {
    const path = val.path;
    if (isHttp(path)) {
      // http(s):// 路径新窗口打开
      const pindex = path.indexOf("http");
      window.open(path.substr(pindex, path.length), "_blank");
    } else {
      router.push(path);
    }
  
    search.value = '';
    options.value = [];
    nextTick(() => {
      show.value = false;
    });
  }
  
  /**
   * 生成可显示在侧边栏的路由
   * @param routes - 路由数组
   * @param basePath - 基础路径
   * @param prefixTitle - 标题前缀
   * @returns 返回处理后的路由数组
   */
  function generateRoutes(routes: any[], basePath: string = '', prefixTitle: string[] = []): any[] {
    let res: any[] = [];
  
    for (const r of routes) {
      // 跳过隐藏的路由
      if (r.hidden) continue;
  
      const p = r.path.length > 0 && r.path[0] === '/' ? r.path : '/' + r.path;
      const data = {
        path: !isHttp(r.path) ? PathUtils.getNormalPath(basePath + p) : r.path, // 使用 PathUtils.getNormalPath
        title: [...prefixTitle]
      };
  
      if (r.meta && r.meta.title) {
        data.title = [...data.title, r.meta.title];
  
        if (r.redirect !== 'noRedirect') {
          // 只推入带有标题的路由
          // 特殊情况：需要排除没有重定向的父路由
          res.push(data);
        }
      }
  
      // 递归处理子路由
      if (r.children) {
        const tempRoutes = generateRoutes(r.children, data.path, data.title);
        if (tempRoutes.length >= 1) {
          res = [...res, ...tempRoutes];
        }
      }
    }
    return res;
  }
  
  /**
   * 远程方法查询搜索
   * @param query - 查询字符串
   */
  function querySearch(query: string) {
    if (query !== '') {
      const results = searchPool.value.filter(item => {
        return item.title.some((title: string)  => title.toLowerCase().includes(query.toLowerCase())) ||
               item.path.toLowerCase().includes(query.toLowerCase());
      });
      options.value = results.map(item => ({ item }));
    } else {
      options.value = [];
    }
  }
  
  // 组件挂载时初始化搜索池
  onMounted(() => {
    searchPool.value = generateRoutes(routes.value);
  });
  
  // 监听路由变化并更新搜索池
  watchEffect(() => {
    searchPool.value = generateRoutes(routes.value);
  });
  
  // 监听 show 变化，添加或移除点击事件监听器
  watch(show, (value: boolean) => {
    if (value) {
      document.body.addEventListener('click', close);
    } else {
      document.body.removeEventListener('click', close);
    }
  });
  
  // 保留 fuse 引用和 initFuse 函数，但注释掉
  // const fuse = ref<FuseType<any> | undefined>();
  
  // /**
  //  * 初始化 Fuse.js
  //  * @param list - 搜索池
  //  */
  // function initFuse(list: any[]) {
  //   fuse.value = new Fuse(list, {
  //     shouldSort: true,
  //     threshold: 0.4,
  //     location: 0,
  //     distance: 100,
  //     minMatchCharLength: 1,
  //     keys: [
  //       { name: 'title', weight: 0.7 },
  //       { name: 'path', weight: 0.3 }
  //     ]
  //   });
  // }
  
  // // 监听搜索池变化并重新初始化 Fuse.js
  // watch(searchPool, (list: any[]) => {
  //   initFuse(list);
  // });
  </script>
  
  <style lang='scss' scoped>
  .header-search {
    font-size: 0 !important;
  
    .search-icon {
      cursor: pointer;
      font-size: 18px;
      vertical-align: middle;
    }
  
    .header-search-select {
      font-size: 18px;
      transition: width 0.2s;
      width: 0;
      overflow: hidden;
      background: transparent;
      border-radius: 0;
      display: inline-block;
      vertical-align: middle;
  
      :deep(.el-input__inner) {
        border-radius: 0;
        border: 0;
        padding-left: 0;
        padding-right: 0;
        box-shadow: none !important;
        border-bottom: 1px solid #d9d9d9;
        vertical-align: middle;
      }
    }
  
    &.show {
      .header-search-select {
        width: 210px;
        margin-left: 10px;
      }
    }
  }
  </style>